package com.wsx.ones.monitor.core.exec.push;

import com.google.common.reflect.AbstractInvocationHandler;
import com.wsx.ones.monitor.common.key.RequestKey;
import com.wsx.ones.monitor.core.loader.RpcClientLoader;
import com.wsx.ones.monitor.core.model.RpcRequest;
import com.wsx.ones.monitor.core.netty.PushMessageHandler;

import java.lang.reflect.Method;

/**
 * 动态代理的核心实现，主要是rpc通信的核心
 *
 * Created by wangshuaixin on 17/2/4.
 */
public class PushProxy<T> extends AbstractInvocationHandler {

    /**
     * 代理的执行方法，在该方法中实现的是netty的通信
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
        //封装请求的对象
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setRequestId(RequestKey.getKey());
        rpcRequest.setClassName(method.getDeclaringClass().getName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setParameterTypes(method.getParameterTypes());
        rpcRequest.setParametes(args);

        //通过netty的adapter来实现netty中的数据传输
        PushMessageHandler push = RpcClientLoader.getInstance().getPushMessageHandler();
        Object obj = push.pushMessage(rpcRequest).doBegin();
        return obj;
    }
}
